package org.kl.bf.web.basic;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletRequest;

import org.kl.bf.entity.basic.User;
import org.kl.bf.service.basic.UserService;
import org.kl.bf.utils.EmailUtil;
import org.kl.bf.utils.MD5Util;
import org.kl.bf.web.base.BasicController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.security.utils.Digests;
import org.springside.modules.utils.Encodes;
import org.springside.modules.web.MediaTypes;

@Controller
@RequestMapping(value = "/basic/userValidate")
public class UserValidateController extends BasicController {

	@Autowired
	private UserService userService;
	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	private static final int SALT_SIZE = 8;

	@RequestMapping(value = "userValidate")
	public String userValidate() {
		return "basic/userValidateList";
	}

	/**
	 * 检验邮箱是否被绑定
	 */
	@RequestMapping(value = "checkUser", method = RequestMethod.GET, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String checkUser(@RequestParam("loginName") String loginName) {
		User user = userService.getByLoginNo(loginName);
		if (user != null) {
			if (user.getStatus() == 1) {
				return ajaxMsg("恭喜，该邮箱可用", true, null);
			} else {
				return ajaxMsg("抱歉，该邮箱还未被激活", false, null);
			}

		} else {
			return ajaxMsg("登录账号输入错误！", false, null);
		}

	}

	/**
	 * 发送邮件
	 */
	@RequestMapping(value = "updateUser")
	public String updateUser(@RequestParam(value = "loginName") String loginName, Model model, RedirectAttributes redirectAttributes,
			ServletRequest request) {
		Random random = new Random();
		int randomCode = random.nextInt(1000000);
		while (randomCode <= 100000) {
			randomCode = random.nextInt(1000000);
		}
		String validateCode = MD5Util.mD5Encode(randomCode + "");

		Timestamp validateTime = new Timestamp(new Date().getTime());
		Timestamp overdueTime = new Timestamp(validateTime.getTime() + 86400000);

		User user = userService.getByLoginNo(loginName);
		user.setValidateCode(validateCode);
		user.setValidateTime(validateTime);
		user.setOverdueTime(overdueTime);
		userService.saveUser(user);

		Map<String, Object> emailMap = new HashMap<String, Object>();
		emailMap.put("qq.com", "http://mail.qq.com/");
		emailMap.put("163.com", "http://email.163.com/");
		emailMap.put("126.com", "http://email.126.com/");
		emailMap.put("21cn.com", "http://mail.21cn.com/");
		emailMap.put("sina.com.cn", "http://mail.sina.com.cn/");
		emailMap.put("sohu.com", "http://mail.sohu.com/");

		String key = user.getEmail().split("@")[1];
		model.addAttribute("http", emailMap.get(key).toString());

		sendEmail(user.getEmail(), validateCode);
		return "basic/userBindingSuccessList";
	}

	/*
	 * 拼接邮件内容
	 */
	private void sendEmail(String email, String validateCode) {

		StringBuffer sb = new StringBuffer("请点击链接找回密码：");
		sb.append("<a href=\"http://localhost:9089/WisdomSchool/basic/userValidate/getPassWord?path=,");
		sb.append(email);
		sb.append(",");
		sb.append(validateCode);
		sb.append("\">http://localhost:9089/WisdomSchool/basic/userValidate/getPassWord?email=");
		sb.append(email);
		sb.append("&validateCode=");
		sb.append(validateCode);
		sb.append("</a></br>");
		sb.append("(该链接在24小时内有效，24小时后需要重新获取)");
		EmailUtil.send(email, sb.toString(), 1);
	}

	/*
	 * 密码找回，转到修改密码页面
	 */
	@RequestMapping(value = "getPassWord")
	public String getPassWord(@RequestParam(value = "path") String path, Model model, RedirectAttributes redirectAttributes,
			ServletRequest request) {
		String email = path.split(",")[1];
		String validateCode = path.split(",")[2];
		model.addAttribute("email", email);
		model.addAttribute("validateCode", validateCode);
		return "basic/useRePairPassWordList";
	}

	/*
	 * 获取页面输入的新密码并且加密
	 */
	@RequestMapping(value = "validateUser", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String validateUser(@RequestParam(value = "email") String email, @RequestParam(value = "validateCode") String validateCode,
			@RequestParam(value = "newPassword") String newPassword, RedirectAttributes redirectAttributes, ServletRequest request) {
		String msg = "";
		User user = userService.findUserByEmail(email);
		Timestamp currentTime = new Timestamp(new Date().getTime());// 获取当前时间
		// 验证链接是否过期
		if (currentTime.before(user.getOverdueTime())) {
			// 验证激活码是否正确
			if (validateCode.equals(user.getValidateCode())) {
				byte[] salt = Digests.generateSalt(SALT_SIZE);
				user.setSalt(Encodes.encodeHex(salt));
				byte[] hashPassword = Digests.sha1(newPassword.getBytes(), salt, HASH_INTERATIONS);
				user.setPassword(Encodes.encodeHex(hashPassword));
				userService.saveUser(user);
				msg = "恭喜您，密码修改成功！";
				return ajaxMsg("success", true, msg);
			} else {
				msg = "激活码不正确！";
				return ajaxMsg("false", false, msg);
			}
		} else {
			msg = "激活链接已失效！";
			return ajaxMsg("false", false, msg);
		}
	}

}
